package com.xiaobai.demo;

import lombok.extern.slf4j.Slf4j;

/*
两阶段终止线程
 */
@Slf4j
public class TwoPhaseTermination {

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true){
                //不会清除打断标志
                boolean interrupted = Thread.currentThread().isInterrupted();
                if (interrupted){
                    log.debug("Thread is interrupted");
                    break;
                }
                try {
                    Thread.sleep(1000); //这个时候被打断的话就会进入到catch中，然后打断标志会重置为false
                    log.debug("执行监控记录");
                } catch (InterruptedException e) {
                    log.error("线程被打断");
                    //线程打断之后会抛出异常，但是打断标志不会被重置
                    Thread.currentThread().interrupt();
                }
            }
        });
        thread.start();
        try {
            Thread.sleep(3500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        thread.interrupt();
    }
}
